package com.example.controller;

import com.example.model.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller  //Spring启动初始化此类
@RequestMapping("/mvc")  //声明路由映射到该类上   基类（ip+端口号）
@Slf4j
@ResponseBody
public class MvcController {

    private Logger logger = LoggerFactory.getLogger(MvcController.class);

    //临时重定向
    @RequestMapping("/index")  //如果省略只能拿到类，不能拿到方法
    public String getIndex(){
        logger.error("我是index.html");
        return "redirect:/index.html";
    }

    //请求转发
    @RequestMapping("/index2")
    public String getIndex2(){
        logger.error("我是请求转发");
        return "forward:/index.html";
    }

    /**
     * 完成301永久重定向跳转
     * @param response
     * @return
     */
    @RequestMapping("/index3")
    public String getIndex3(HttpServletResponse response){
        response.setStatus(301);
        response.setHeader("Location","http://localhost:8080/index.html");
        return null;
    }

    @GetMapping("/index4")  //只能通过get方式访问
    public String getIndex4(){
        logger.error("我是index.html");
        return "/index.html";
    }

    @PostMapping("/index5")
    public String getIndex5(){
        logger.error("我是index.html");
        return "/index.html";
    }

    @RequestMapping("/index6")
    @ResponseBody  //返回自定义类型而非视图
    public  String getIndex6(){
        return "/index.html";
    }

    @Autowired
    private ObjectMapper objectMapper;

    @RequestMapping("/index7")
    @ResponseBody
    public String getIndex7() throws JsonProcessingException {
        User user = new User();
        user.setUsername("trq");
        user.setPassword("hello");
        //将对象转换成Json字符串
        String result = objectMapper.writeValueAsString(user);
        log.error(result);
        return result;
    }


    @RequestMapping("/index8")
    @ResponseBody
    //利用Spring技术直接转换成了Json对象，非常方便
    public User getIndex8(){
        User user = new User();
        user.setUsername("trq");
        user.setPassword("hello");
        return user;
    }

    @RequestMapping(value = "/index9", method = RequestMethod.GET)
    public String getIndex9(){
        return "/index.html";
    }





}
